package com.wulaobo.state;

import com.wulaobo.constant.Constants;
import com.wulaobo.functions.WaterSensorMapFunction;
import com.wulaobo.pojo.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author wuwenbo
 * @Date 2024/7/10 13:57
 * @ClassName: KeyedReducingStateDemo
 * @Description: 案例：计算每种传感器的水位和
 */
public class KeyedReducingStateDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream(Constants.IP, 7777)
                .map(new WaterSensorMapFunction());

        sensorDS.keyBy(WaterSensor::getId).process(new KeyedProcessFunction<String, WaterSensor, String>() {

            ReducingState<Integer> reducingState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);

                // TODO 2.在open方法中，初始化状态
                // 状态描述器两个参数：第一个参数，起个名字，不重复；第二个参数，存储的类型
                reducingState = getRuntimeContext().getReducingState(new ReducingStateDescriptor("reducingState", new ReduceFunction<Integer>() {
                    @Override
                    public Integer reduce(Integer value1, Integer value2) throws Exception {
                        return value1+value2;
                    }
                }, Integer.class));

            }

            @Override
            public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                out.collect("key:"+value.getId()+",聚合前的水位值为："+reducingState.get());
                reducingState.add(value.getTs());
                out.collect("key:"+value.getId()+",聚合后的水位值为："+reducingState.get());

            }

        }).print();

        env.execute();

    }

}
